const express = require('express');
const router = express.Router();
const {md5,formatTime} = require('../util/common');
const {mysqlQuery} = require('../util/mysql');
const JwtUtil=require('../util/jwt');
const { GetServerList, AddServerList, UpdateServerList, DelServerList } = require('../util/index.js');

router.post('/login', (req, res) => {
    let params = req.body;
    if(typeof params['username']=='undefined' || params['username']==''){
        res.json({status: false,msg:'用户名不能为空'});
        return;
    }
    if(typeof params['password']=='undefined' || params['password']==''){
        res.json({status: false,msg:'密码不能为空'});
        return;
    }
    mysqlQuery("select * from user where username='"+params['username']+"'").then(response => {
        let result={status: false,msg:'用户名或密码错误'};
        if(response.length>0 && response[0]['password']==md5(params['password'])){
            mysqlQuery("UPDATE user SET last_login_time='"+formatTime(new Date())+"' where id='"+response[0]['id']+"'")
            let jwt = new JwtUtil(response[0]['id']);
            let token = jwt.generateToken();
            delete response[0]['password'];
            result={status: true,token:token,user:response[0]};
        }
        res.json(result);
    }).catch(e => {
        console.log(e);
        res.json({status: false,msg:'数据库异常'})
    })
});

router.post('/token',(req,res)=>{
    let token = req.headers.token;
    let jwt = new JwtUtil(token);
    let result = jwt.verifyToken();
    if (result == 'err') {
        res.send({status:false,reLogin:true, msg: '登录已过期,请重新登录'});
    } else {
        let jwt = new JwtUtil(result);
        let token = jwt.generateToken();
        res.json({status:true,token:token});
    }
});

router.all('/GetServerList', GetServerList);

router.all('/AddServerList', AddServerList);

router.all('/UpdateServerList', UpdateServerList);

router.all('/DelServerList', DelServerList)

module.exports = router;